<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.keyword" clearable placeholder="权限或权限标识名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
      <div style="float:right;">
        <el-button size="mini" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-error" @click="handleFreeze">快速冻结</el-button>
        <el-button v-waves size="mini" :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-circle-plus-outline" @click="handleCreate">新增</el-button>
        <el-button v-waves size="mini" :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-edit" @click="handleEditdata()">编辑</el-button>
        <el-button v-waves size="mini" :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-delete" @click="handleDelete()">删除</el-button>
      </div>
    </div>
    <el-table
      ref="dataTable"
      :key="tableKey"
      v-loading="listLoading"
      stripe
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :row-class-name="tableRowClassName"
      @current-change="handleCurrentChange"
      @sort-change="sortChange"
    >
      <el-table-column label="序号" width="50" align="center">
        <template slot-scope="{row}">
          {{ row.index+1 }}
        </template>
      </el-table-column>
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="60" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column label="头像" min-width="100px">-->
      <!--<template slot-scope="{row}">-->
      <!--<span class="link-type">{{ row.avatar }}</span>-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column label="权限名称" width="100px" align="left">
        <template slot-scope="{row}">
          <span>{{ row.cnname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="权限状态" width="110px" align="center">
        <template slot-scope="{row}">
          <el-tag v-if="row.available" type="success">正常</el-tag>
          <el-tag v-else type="danger">冻结</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="权限标识" width="120px">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column label="拥有该权限的角色" min-width="110px" max-width="200px" align="left">-->
        <!--<template slot-scope="{row}">-->
          <!--<el-tag-->
            <!--v-for="(item, index) in row.cnroles"-->
            <!--:key="index"-->
            <!--style="margin-top: 0px !important;margin-right: 15px !important;"-->
            <!--type="info"-->
          <!--&gt;{{ item }}-->
          <!--</el-tag>-->
        <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column label="备注" min-width="120px">
        <template slot-scope="{row}">
          <span>{{ row.remark }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column label="Actions" align="center" width="320" class-name="small-padding fixed-width">-->
      <!--<template slot-scope="{row,$index}">-->
      <!--<el-button type="primary" size="mini">-->
      <!--锁定-->
      <!--</el-button>-->
      <!--<el-button size="mini" type="success" @click="handleUpdate(row,'published')">-->
      <!--编辑-->
      <!--</el-button>-->
      <!--<el-button size="mini">-->
      <!--重置密码-->
      <!--</el-button>-->
      <!--<el-button size="mini" type="danger" @click="handleDelete(row,$index)">-->
      <!--删除-->
      <!--</el-button>-->
      <!--</template>-->
      <!--</el-table-column>-->
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 40vw; margin-left:50px;">
        <el-form-item label="权限状态">
          <el-radio-group v-model="temp.available" size="small" name="enabled">
            <el-radio :label="true" border>正常</el-radio>
            <el-radio :label="false" border>冻结</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="权限名称" prop="cnname">
          <el-input v-model="temp.cnname" name="cnname" />
        </el-form-item>
        <!--<el-form-item label="Remark">-->
        <!--<el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />-->
        <!--</el-form-item>-->
        <el-form-item label="权限标识" prop="name">
          <el-input v-model="temp.name" name="name" />
        </el-form-item>
        <el-form-item label="备注说明">
          <el-input v-model="temp.remark" name="remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="备注权限的说明" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='创建'?createData():updateData()">
          确定提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { APIindex, APIstore, APIupdate, APIdestroy, APIFreeze } from '@/api/sysPermission'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'Table',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        keyword: undefined,
        type: undefined,
        sort: undefined
      },
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      temp: {
        id: undefined,
        name: '',
        cnname: '',
        available: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        name: [{ required: true, message: '需要权限名称', trigger: 'blur' }],
        cnname: [{ required: true, message: '需要权限标识-页面标识', trigger: 'blur' }]
      },
      downloadLoading: false,
      rowdata: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      APIindex(this.listQuery).then(response => {
        this.list = response.data.content
        for (const data of this.list) {
          // const arr = []
          // const cnarr = []
          // for (const role of data.roles) {
          //   cnarr.push(role.cnname)
          //   arr.push(role.role)
          // }
          if (data.createdAt != null) {
            data.createdAt = data.createdAt.substring(0, data.createdAt.length - 4)
          }
          // data.cnroles = cnarr
          // data.roles = arr
        }
        this.total = response.data.totalElements
        // console.log(this.list)
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        cnname: '',
        available: false
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = '创建'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          APIstore(this.temp).then(response => {
            this.temp.id = response.data.id
            this.temp.createdAt = response.data.createdAt
            this.temp.updatedAt = response.data.updatedAt
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功！',
              message: '添加成功！',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = '编辑'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          APIupdate(tempData.id, tempData).then(response => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.temp.id = response.data.id
            // 因为角色 cnroles 是分离 role 的所以这里也要同步更新一下 cnroles
            // const cnarr = []
            // for (const role of response.data.roles) {
            //   cnarr.push(role.cnname)
            // }
            // this.temp.cnroles = cnarr
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功！',
              message: '更新成功！',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      // 先提示，是否确定删除
      if (!this.rowdata) {
        this.$alert('请选中一条数据', '提示', {
          confirmButtonText: '确定'
        })
        return
      }
      // 开始提示是否确认删除
      this.$confirm('删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        APIdestroy(this.rowdata.id).then(() => {
          this.list.splice(this.rowdata.index, 1)
          this.$notify({
            title: '删除成功！',
            message: '删除成功！',
            type: 'success',
            duration: 2000
          })
        })
      }).catch(() => {
        this.$notify({
          title: '取消操作',
          message: '取消删除操作',
          type: 'success',
          duration: 2000
        })
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    handleCurrentChange(val) {
      this.rowdata = val
      // console.log(this.dataindex)
      // console.log(val)
    },
    handleEditdata() {
      if (!this.rowdata) {
        this.$alert('请选中一条数据', '提示', {
          confirmButtonText: '确定'
        })
        return
      }
      this.temp = Object.assign({}, this.rowdata) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = '编辑'
      this.dialogFormVisible = true
      // console.log(this.temp)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    tableRowClassName({ row, rowIndex }) {	// 行元素，行索引
      row.index = rowIndex
    },
    handleFreeze() {	// 行元素，行索引
      if (!this.rowdata) {
        this.$alert('请选中一条数据', '提示', {
          confirmButtonText: '确定'
        })
        return
      }
      this.temp = Object.assign({}, this.rowdata) // copy obj
      this.$confirm('冻结该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        APIFreeze(this.temp.id).then(() => {
          this.temp.available = false
          this.list.splice(this.temp.index, 1, this.temp)
          this.$notify({
            title: '冻结成功！',
            message: '冻结成功！',
            type: 'success',
            duration: 2000
          })
        })
      }).catch(() => {
        this.$notify({
          title: '取消操作',
          message: '取消冻结操作',
          type: 'success',
          duration: 2000
        })
      })
      // 先确定一下，是否冻结，如果是就立即冻结
    }
  }
}
</script>
